package cn.main.service.impl;

import cn.main.core.AuthorityHelper;
import cn.main.core.UserSession;
import cn.main.dao.DomainDao;
import cn.main.entity.sys.SysColumn;
import cn.main.entity.sys.SysFunction;
import cn.main.service.FunctionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author: chengwei
 * Date:   2016/7/13
 * Time:   11:34
 */
@Service
public class FunctionServiceImpl implements FunctionService {
    @Resource
    private DomainDao dao;

    @Override
    @Transactional
    public void saveOrUpdateFunction(UserSession session, SysFunction function) {
        dao.saveDomain(function);
    }

    @Override
    @Transactional
    public void deleteFunction(UserSession session,String functionId) {
        SysFunction function = new SysFunction();
        function.setFunctionId(functionId);
        dao.deleteDomain(function);
    }

    public SysFunction findFunctionById(UserSession session,String functionId) {
        
        dao.setCacheQueries(true);
        SysFunction function =  dao.getDomain(functionId,SysFunction.class);
        //判断权限
        if (AuthorityHelper.hasFunctionAuthority(session,function)) {
            function.setColumn(null);
            function.setRoles(null);
            return function;
        }
        return null;
    }

    @Override
    public List<SysFunction> getFunctionList(UserSession session) {
        dao.setCacheQueries(true);
        List<SysFunction> functions = dao.getDomains(SysFunction.class,"order by show_order");
        for (int i = functions.size()-1;i >= 0;i--) {
            if (!AuthorityHelper.hasFunctionAuthority(session,functions.get(i))) {
                functions.remove(i);
                continue;
            }
            functions.get(i).setRoles(null);
            functions.get(i).setColumn(null);
        }
        return functions;
    }

    @Override
    public List<SysFunction> getFunctionList(String columnId) {
        dao.setCacheQueries(true);
        List<SysFunction> functions = dao.getDomains(SysFunction.class,"where column.columnId = ? order by show_order",columnId);
        for (int i = functions.size()-1;i >= 0;i--) {
            functions.get(i).setRoles(null);
            functions.get(i).setColumn(null);
        }
        return functions;
    }
}
